package top.shenluw.springdemo.jpa;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Shenluw
 * created：2019/7/22 13:42
 */
@Service
public class UserService {

	@Autowired
	UserRepository userRepository;

	@Transactional
	public Object updateAge(int id) {
		User user = userRepository.findByIdForWriteLock(id);
		user.setAge(user.getAge() + 1);
		sleep();
		return userRepository.save(user);
	}

	public User findByNoLock(int id) {
		User user = userRepository.findById(id).orElse(null);
		sleep();
		return user;
	}

	@Transactional
	public User findByReadLock(int id) {
		User user = userRepository.findByIdForReadLock(id);
		sleep();
		return user;
	}

	private void sleep() {
		// 表示这个事务比较耗时
		try {
			Thread.sleep(100);
		} catch (InterruptedException e) {
		}
	}

}
